<template>
    <search v-model:options="searchOptions" @submit="searchSubmit"></search>
    <div class="task">
      <t-card :bordered="false">
        <div>
          <t-button v-auth="'sys:notice:add'" @click="onAddHander">{{ $t('menu.sys:notice:add') }}</t-button>
        </div>
        <t-table
          stripe
          ref="tableRef"
          :data="noticeData"
          :columns="columns"
          row-key="id"
          :loading="tableLoading"
          :pagination="pagination"
          @change="rehandleChange"
          @page-change="onPageChange"
        />
      </t-card>
      <t-dialog v-model:visible="noticeFromVisible" :footer="false" width="1000" top="20px">
        <template #header>{{ $t('menu.sys:notice:add') }}</template>
        <noticeFrom ref="noticeFromRef" @submit-hook="onSubmitHook"></noticeFrom>
      </t-dialog>
    </div>
  </template>
  <script setup lang="tsx">
  import {CheckIcon, CloseIcon} from 'tdesign-icons-vue-next';
  import {DropdownProps, MessagePlugin} from 'tdesign-vue-next';
  import {PaginationProps} from 'tdesign-vue-next/es/pagination';
  import {PrimaryTableCol} from 'tdesign-vue-next/es/table/type';
  import {computed, onMounted, reactive, ref} from 'vue';
  
  import {getMonitorList,changeStatus} from '@/api/monitor/task';
  import {PageTask, Task} from '@/api/monitor/task/types';
  import {Notice, PageNoticeReq, PageNoticeRes} from '@/api/system/notice/types';
  import {delNotice, noticePage} from '@/api/system/notice';
  import search, {SearchOption} from '@/components/search/index.vue';
  import {ResultEnum} from '@/enums/httpEnum';
  import {hasAuth, useAuth} from '@/hooks/auth';
  import i18n from '@/i18n';
  import {useSettingStore} from '@/store';
  import { SYS_NOTICE_STATUS, SYS_NOTICE_TARGET, SYS_NOTICE_TYPE } from '@/constants/dictTypes';
  import { formatByMomentTimezone } from '@/utils/date';
  import noticeFrom from './components/noticeFrom.vue';
  
  // 查询表单
  const pageParams = ref<PageNoticeReq>({
  pageNumber: 1,
  pageSize: 10,
  title: '',
  operators: '',
  type: undefined,
  target: undefined,
  expire: undefined,
  });
  // 表格数据ref
  const tableRef=ref();
  
  // 分页参数
  const pagination: PaginationProps = reactive({
    total: 0,
    pageEllipsisMode: 'mid',
    maxPageBtn: 5,
  });
  
  // 表格字段
  const columns: Array<PrimaryTableCol<PageNoticeRes>> = [
    {
      colKey: 'serial-number',
      title: () => i18n.global.t('common.attribute.serialNumber'),
    },
    {
      colKey: 'title',
      title: () => i18n.global.t('sys.notice.label.from.title'),
      minWidth: 100,
    },
    {
      colKey: 'type',
      title: () => i18n.global.t('sys.notice.label.from.type'), 
      minWidth: 100,
      cell:  (h, { row }) => (
      <div>
      {
        <tagDict dictType={SYS_NOTICE_TYPE} value={row.type}></tagDict>
      }
      </div>
    ),
    },
    {
      colKey: 'target',
      title: () => i18n.global.t('sys.notice.label.target'),
      minWidth: 100,
      cell:  (h, { row }) => (
      <div>
      {
        <tagDict dictType={SYS_NOTICE_TARGET} value={row.target}></tagDict>
      }
      </div>
    ),
    },
    {
      colKey: 'expire',
      title: () => i18n.global.t('sys.notice.label.expire'),
      minWidth: 100,
      cell:  (h, { row }) => (
        <div>
        {
          
          row.expire?formatByMomentTimezone(row.expire,'YYYY-MM-DD'):''
          
        }
        </div>
      ),
    },
    {
      colKey: 'status',
      title: () => i18n.global.t('sys.notice.label.status'),
      minWidth: 70,
      cell:  (h, { row }) => (
        <div>
        {
          <tagDict dictType={SYS_NOTICE_STATUS} value={row.status}></tagDict>
        }
        </div>
      ),
    },
    {
      colKey: 'operate',
      title: () => i18n.global.t('common.operate'),
      // 增、删、改、查 等操作
      cell: (h, {row}) => (
        <t-space>
          {

          useAuth('sys:notice:edit', <t-link theme="primary" variant="text" hover="color" onClick={() => onEditHander(row)}>
            {i18n.global.t('common.button.edit')}
          </t-link>)
          }
          {
          useAuth('sys:notice:remove', <t-popconfirm content={() => i18n.global.t('common.label.sureDelete')} onConfirm={() => onDelHander(row)}>
            <t-link variant="text" hover="color" theme="danger">
              {i18n.global.t('common.button.delete')}
            </t-link>
          </t-popconfirm>)
          }
        </t-space>
      ),
    },
  ];
  
  // 分页列表数据
  const noticeData = ref<PageNoticeRes[]>([]);
  const settingStore = useSettingStore();
  const tableLoading = ref(false);
  
  // 控制租户编辑表单标量
  const noticeFromRef = ref();
  const noticeFromVisible = ref(false);
  
  /**
   * 添加通知适配器
   */
  const onAddHander = () => {
    noticeFromRef.value.initFromData();
    noticeFromVisible.value = true;
  };
  
  /**
   * 编辑通知适配器
   */
  const onEditHander = (row: Notice) => {
    noticeFromRef.value.initFromData(row.id);
    noticeFromVisible.value = true;
  };

  /**
   * 删除通知适配器
   */
  const onDelHander = async (row: Notice) => {
    const { code } = await delNotice(row.id);
    if (ResultEnum.SUCCESS === code) {
      MessagePlugin.success(i18n.global.t('common.messages.deleteSuccess'));
      loadData();
    }
  };
  
  // BaseTable 中只有 page-change 事件，没有 change 事件
  const rehandleChange = (changeParams: any, triggerAndData: any) => {
    console.debug('分页、排序、过滤等发生变化时会触发 change 事件：', changeParams, triggerAndData);
  };
  
  // BaseTable 中只有 page-change 事件，没有 change 事件
  const onPageChange = async (pageInfo: PaginationProps) => {
    pageParams.value.pageNumber = pageInfo.current;
    pageParams.value.pageSize = pageInfo.pageSize;
    loadData();
  };

  
  
  /**
   * 加载表格数据
   */
  const loadData = async () => {
    tableLoading.value = true;
    const {code, result, message} = await noticePage(pageParams.value);
    if (code === ResultEnum.SUCCESS) {
      noticeData.value = result.records;
      pagination.total = result.totalRow;
    }
    tableLoading.value = false;
  };
  
  /**
   * 新增/修改成功后的回调事件
   */
  const onSubmitHook = () => {
    noticeFromVisible.value = false;
    loadData();
  };
  
  const showBreadcrumbHeight = computed(() => {
    return settingStore.showBreadcrumb ? '46px' : '0px';
  });
  
  // 查询组件配置
  const searchOptions = ref<SearchOption[]>([
    {
      name: 'roleName',
      value: '',
      label: computed(() => i18n.global.t('role.label.name')),
      placeholder: computed(() => i18n.global.t('role.label.pl.name')),
      type: 'input',
    },
    {
      name: 'roleCode',
      value: '',
      label: computed(() => i18n.global.t('role.label.code')),
      placeholder: computed(() => i18n.global.t('role.label.pl.code')),
      type: 'input',
    },
  ]);
  
  onMounted(async () => {
    loadData();
  });
  
  const searchSubmit = (params: PageTask) => {
    loadData();
  };
  </script>
  <style scoped lang="less">
  .task {
    // background: #fff;
    min-height: calc(100% - v-bind(showBreadcrumbHeight));
    display: flex;
  
    .t-card {
      width: 100%;
    }
  }
  </style>
  